package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.OrderTypeEnum;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 退费申请 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2025-04-22
 */
@Service
public class AuditReturnPremiumServiceImpl extends ServiceImpl<AuditReturnPremiumMapper, AuditReturnPremium> implements IAuditReturnPremiumService {

    @Autowired
    AuditReturnPremiumMapper auditReturnPremiumMapper;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IOrderReturnTeacherService iOrderReturnTeacherService;

    @Autowired
    @Lazy
    ICoursePricingService iCoursePricingService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IOrderTransferService iOrderTransferService;

    @Autowired
    @Lazy
    IOrderTransferDetailService iOrderTransferDetailService;

    @Autowired
    @Lazy
    OrderApplyMapper orderApplyMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    IStudentSchoolService iStudentSchoolService;

    @Autowired
    @Lazy
    EnrollInfoMapper enrollInfoMapper;

    @Autowired
    @Lazy
    IRatePayService iRatePayService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    IOrderReturnCauseService iOrderReturnCauseService;

    @Autowired
    ICommonCauseService iCommonCauseService;


    @Override
    public IPage<AuditReturnPremium> getAuditReturnPremiumList(IPage<?> page,
                                                               String yearPart,
                                                               String quarterNum,
                                                               String schoolId,
                                                               String subjectsId,
                                                               String studentName,
                                                               String startDate,
                                                               String endDate,
                                                               String returnType,
                                                               String status,
                                                               String adminId) {
        return auditReturnPremiumMapper.getAuditReturnPremiumList(page, yearPart, quarterNum, schoolId, subjectsId, studentName, startDate, endDate, returnType, status, adminId);
    }

    @Override
    public AuditReturnPremium getAuditReturnPremiumDetails(Long id) {
        return auditReturnPremiumMapper.getAuditReturnPremiumDetails(id);
    }


    @Override
    @Transactional
    public boolean updateReturnPremium(AuditReturnPremium auditReturnPremium, Long adminId) {
        Long subjectsId = auditReturnPremium.getSubjectsId();
        Long studentId = auditReturnPremium.getStudentId();
        Long schoolId = auditReturnPremium.getSchoolId();
        //申请退出多少课时
        Integer returnCourseCount = auditReturnPremium.getReturnCourseCount();
        //学生一共剩余多少课时
        Integer residueCourseCount = auditReturnPremium.getResidueCourseCount();

        List<OrderDetail> orderDetailList = iOrderDetailService.getResidueOrderDetail(auditReturnPremium.getSchoolId(), auditReturnPremium.getStudentId(), auditReturnPremium.getSubjectsId(), 1);

        OrderTransfer orderTransfer = new OrderTransfer();
        orderTransfer.setOutSchoolId(auditReturnPremium.getSchoolId());
        orderTransfer.setOutType(1);
        orderTransfer.setOrderType(4);

        Integer outHouse = 0;
        BigDecimal outPrice = new BigDecimal(0.00);

        Integer returnType = 1;//全部退出

        //部分退出计算使用
        Integer notReturnCount = returnCourseCount;//未退出还有多少课时

        //部分退出
        if (auditReturnPremium.getReturnType().equals(2)) {
            //部分退出，如果申请的部门退出的课时大于等于剩余课时，相当于是全部退出
            if (auditReturnPremium.getReturnCourseCount() >= residueCourseCount) {
                returnType = 1;
            } else {
                returnType = 2;
            }
        }

        List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();

        //Integer residueCourseCountDiff = residueCourseCount;
        //全部退出
        if (returnType.equals(1)) {
            for (OrderDetail orderDetail : orderDetailList) {
                orderTransfer.setOutGradeId(orderDetail.getCourseId());
                OrderTransferDetail orderTransferDetail = new OrderTransferDetail();
                orderTransferDetail.setMaterialsPrice(new BigDecimal(0.00));
                orderTransferDetail.setOldOrderId(orderDetail.getOrderId());
                orderTransferDetail.setOldOrderDetailId(orderDetail.getId());
                orderTransferDetail.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
                orderTransferDetail.setOutHouse(orderDetail.getResidueCourseCount());
                orderTransferDetail.setOutPrice(orderDetail.getResiduePrice());
                outHouse += orderDetail.getResidueCourseCount();
                outPrice = outPrice.add(orderDetail.getResiduePrice());
                orderTransferDetailList.add(orderTransferDetail);
            }
        } else {
            //部分退出
            for (OrderDetail orderDetail : orderDetailList) {
                if (notReturnCount > 0) {
                    Integer outHouseTemp = 0;
                    BigDecimal outPriceTemp = new BigDecimal(0.00);

                    if (orderDetail.getResidueCourseCount() <= notReturnCount) {
                        outHouseTemp = orderDetail.getResidueCourseCount();
                        outPriceTemp = orderDetail.getResiduePrice();
                    } else {
                        outHouseTemp = notReturnCount;
                        BigDecimal unitPrice = new BigDecimal(173);//默认173
                        CoursePricing coursePricing = iCoursePricingService.getCoursePricingByCourseId(orderDetail.getCourseId(), orderDetail.getSchoolId(), 3);
                        BigDecimal allPrice = new BigDecimal(0.00);
                        if (!Objects.nonNull(coursePricing)) {
                            unitPrice = coursePricing.getUnitPrice();
                        }
                        Integer unitOutHouse = outHouseTemp / 3;
                        allPrice = unitPrice.multiply(new BigDecimal(unitOutHouse));
                        if (allPrice.compareTo(orderDetail.getResiduePrice()) > 0) {
                            outPriceTemp = orderDetail.getResiduePrice();
                        } else {
                            outPriceTemp = allPrice;
                        }
                    }

                    if (outPriceTemp.compareTo(auditReturnPremium.getReturnCoursePrice())>0){
                        outPriceTemp = auditReturnPremium.getReturnCoursePrice();//如果退出金额大于申请金额，使用申请金额
                    }

                    orderTransfer.setOutGradeId(orderDetail.getCourseId());
                    OrderTransferDetail orderTransferDetail = new OrderTransferDetail();
                    orderTransferDetail.setMaterialsPrice(new BigDecimal(0.00));
                    orderTransferDetail.setOldOrderId(orderDetail.getOrderId());
                    orderTransferDetail.setOldOrderDetailId(orderDetail.getId());
                    orderTransferDetail.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
                    orderTransferDetail.setOutHouse(outHouseTemp);
                    orderTransferDetail.setOutPrice(outPriceTemp);
                    outHouse += outHouseTemp;
                    outPrice = outPrice.add(outPriceTemp);
                    notReturnCount = notReturnCount - outHouseTemp;
                    orderTransferDetailList.add(orderTransferDetail);
                    //residueCourseCountDiff = residueCourseCountDiff - outHouseTemp;
                }
            }
        }
        orderTransfer.setOutHouse(outHouse / 3);
        orderTransfer.setOutPrice(outPrice);
        orderTransfer.setOutType(auditReturnPremium.getReturnType());// 1全部转出，2部分转出

        OrderApply orderApply = new OrderApply();
        orderApply.setCostType(2);
        orderApply.setHandleDate(LocalDate.now());
        orderApply.setYearPart(auditReturnPremium.getYearPart());
        orderApply.setQuarterNum(auditReturnPremium.getQuarterNum());
        orderApply.setSubjectsIdStr(String.valueOf(subjectsId));
        orderApply.setSchoolId(schoolId);
        orderApply.setHandleSchoolId(schoolId);
        String schoolName = iOrganizationService.getSchoolName(schoolId);
        orderApply.setHandleSchoolName(schoolName);
        orderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
        orderApply.setOwnPrice(new BigDecimal(0.00));
        orderApply.setPrice(outPrice);
        orderApply.setSolidPrice(outPrice);
        orderApply.setStudentId(studentId);

        orderApply.setOrderTransfer(orderTransfer);
        orderApply.setOrderTransferDetailList(orderTransferDetailList);
        List<OrderPayAccount> orderPayAccountList = new ArrayList<>();
        OrderPayAccount orderPayAccount = new OrderPayAccount();
        orderPayAccount.setAccounType(1);
        orderPayAccount.setAccountTypeName("现金");
        orderPayAccount.setPrice(outPrice);
        orderPayAccountList.add(orderPayAccount);
        orderApply.setOrderPayAccountList(orderPayAccountList);

        orderApply.setHandlePersonId(adminId);
        Staff staff = staffMapper.findOneById(adminId);
        if (staff != null) {
            orderApply.setHandlePersonName(staff.getName());
        }
        Integer receiptNo = CommonUtil.getReceiptNo();
        orderApply.setReceiptNo(receiptNo.toString());

        OrderApply orderApplyReturn = this.refundSave(orderApply);

        Long returnOrderId = orderApplyReturn.getId();

        auditReturnPremium.setSolidReturnCount(outHouse);
        auditReturnPremium.setSolidReturnPrice(outPrice);
        auditReturnPremium.setOrderId(returnOrderId);
        this.updateById(auditReturnPremium);

        OrderReturnCause iOrderReturnCause = iOrderReturnCauseService.getOne(new QueryWrapper<OrderReturnCause>()
                .eq("return_premium_id", auditReturnPremium.getId())
                .eq("order_id", returnOrderId)
                .last(" limit 1"));

        CommonCause commonCause = iCommonCauseService.getById(auditReturnPremium.getCauseId());

        if (iOrderReturnCause == null) {
            iOrderReturnCause = new OrderReturnCause();
            iOrderReturnCause.setOrderId(returnOrderId);
            iOrderReturnCause.setReturnPremiumId(auditReturnPremium.getId());
        }

        iOrderReturnCause.setCauseId(auditReturnPremium.getCauseId());
        iOrderReturnCause.setCauseContent(commonCause.getContent());
        iOrderReturnCauseService.saveOrUpdate(iOrderReturnCause);

        return true;
    }

    /**
     * 退费
     */
    public OrderApply refundSave(OrderApply orderApply) {

        Integer orderType = orderApply.getOrderType().getKey();
        OrderTransfer orderTransfer = orderApply.getOrderTransfer();
        orderApply.setSchoolId(orderApply.getHandleSchoolId());//所属校区

        if (orderApply.getDisPrice() != null && orderApply.getDisPrice().compareTo(new BigDecimal(0)) > 0) {
            orderApply.setDiscountsDate(LocalDate.now());
        }
        if (orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_REFUND)) {
            orderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_REFUND);
        }
        orderApplyMapper.insert(orderApply);

        String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元

        if (orderType == Code.ORDER_TYPE_REFUND && orderTransfer != null) {
            orderTransfer.setOrderId(orderApply.getId());
            iOrderTransferService.save(orderTransfer);
            Course outCourse = iCourseService.getById(orderTransfer.getOutGradeId());
            tradeContent += "退费：" + outCourse.getName() + "退" + orderTransfer.getOutHouse() + "课次，应退学费" + orderTransfer.getOutPrice() + "元";
        }

        Integer yearPart = orderApply.getYearPart();
        Integer quarterNum = orderApply.getQuarterNum();
        String subjectsId = orderApply.getSubjectsIdStr();

        Integer yearClassId = null;
        Set<String> subjectsIdSet = new HashSet<>();

        Boolean isAll = true;//是否全部退出

        Iterator<OrderTransferDetail> orderTransferDetailIterator = orderApply.getOrderTransferDetailList().iterator();
        while (orderTransferDetailIterator.hasNext()) {
            OrderTransferDetail orderTransferDetail = orderTransferDetailIterator.next();
            orderTransferDetail.setOrderType(orderApply.getOrderType());
            orderTransferDetail.setOrderId(orderApply.getId());//设置对应的新订单id

            //退费
            OrderDetail orderDetail = iOrderDetailService.getById(orderTransferDetail.getOldOrderDetailId());

            if (orderDetail != null) {

                OrderDetail newOrderDetail = new OrderDetail();
                newOrderDetail.setId(orderDetail.getId());
                Integer outCourseHouse = orderTransferDetail.getOutHouse();
                Integer courseHouse = orderDetail.getResidueCourseCount() - outCourseHouse;//剩余课时
                //退费课时不能大于剩余课时
                if (courseHouse < 0) {
                    throw new CommonException(ResultCode.REFUND_COURSE_BIG);
                } else if (courseHouse == 0) {
                    try {
                        // 记上课表里使用课时为0，就把排班删除，如果记上课表里使用不为0，如果排班里is_last为1的排班使用课时为0，就删除这条排班，把使用课时大于0的最后一条排班is_last设置为1
                        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                        recordCourseQueryWrapper.eq("student_id", orderApply.getStudentId());
                        recordCourseQueryWrapper.eq("year_part", orderDetail.getYearPart());
                        recordCourseQueryWrapper.eq("quarter", orderDetail.getQuarterNum());
                        recordCourseQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
                        recordCourseQueryWrapper.eq("lesson_type", 1);
                        recordCourseQueryWrapper.eq("status", 1);
                        Long recordCourseCount = iRecordCourseService.count(recordCourseQueryWrapper);

                        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                        studentGradeQueryWrapper.eq("student_id", orderApply.getStudentId());
                        studentGradeQueryWrapper.eq("year_part", orderDetail.getYearPart());
                        studentGradeQueryWrapper.eq("quarter_num", orderDetail.getQuarterNum());
                        studentGradeQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
                        studentGradeQueryWrapper.eq("lesson_type", 1);
                        studentGradeQueryWrapper.eq("deleted", 0);
                        Long studentGradeCount = iStudentGradeService.count(studentGradeQueryWrapper);

                        if (studentGradeCount == 1) {
                            studentGradeQueryWrapper.eq("is_last", 1);
                            StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                            if (studentGrade != null) {
                                if (recordCourseCount == 0) {
                                    if (studentGrade.getUseCourseCount().equals(0)){
                                        // 删除排班数据
                                        iStudentGradeService.removeById(studentGrade);
                                    }
                                }
                            }
                        } else if (studentGradeCount > 1) {
                            List<StudentGrade> studentGrades = iStudentGradeService.list(studentGradeQueryWrapper);
                            for (StudentGrade studentGrade : studentGrades) {
                                if (studentGrade.getUseCourseCount() == 0) {
                                    iStudentGradeService.removeById(studentGrade);
                                } else if (studentGrade.getUseCourseCount() > 0) {
                                    //更新为最后一条
                                    QueryWrapper<StudentGrade> studentGradeQueryWrapperNew = new QueryWrapper<>();
                                    studentGradeQueryWrapperNew.eq("year_part", studentGrade.getYearPart());
                                    studentGradeQueryWrapperNew.eq("quarter_num", studentGrade.getQuarterNum());
                                    studentGradeQueryWrapperNew.eq("student_id", studentGrade.getStudentId());
                                    studentGradeQueryWrapperNew.ne("status", 3);
                                    studentGradeQueryWrapperNew.eq("subjects_id", studentGrade.getSubjectsId());
                                    studentGradeQueryWrapperNew.eq("lesson_type", studentGrade.getLessonType());
                                    studentGradeQueryWrapperNew.orderByDesc("id");
                                    List<StudentGrade> studentGradeListNew = iStudentGradeService.list(studentGradeQueryWrapperNew);
                                    Integer i = 0;
                                    for (StudentGrade studentGradeNew : studentGradeListNew) {
                                        if (i == 0) {
                                            studentGradeNew.setIsLast(1);
                                            studentGradeNew.setReadingStatus(ReadingStatusEnum.RETREAT);// 调整为退费
                                        } else {
                                            studentGradeNew.setIsLast(0);
                                        }
                                        iStudentGradeService.updateById(studentGradeNew);
                                        i++;
                                    }
                                    studentGradeQueryWrapperNew.clear();
                                }
                            }
                        }

                        // 退费删除智能课、刷题班的排班数据
                        QueryWrapper<StudentGrade> studentGradeQueryWrapper2 = new QueryWrapper<>();
                        studentGradeQueryWrapper2.eq("student_id", orderApply.getStudentId());
                        studentGradeQueryWrapper2.eq("year_part", orderDetail.getYearPart());
                        studentGradeQueryWrapper2.eq("quarter_num", orderDetail.getQuarterNum());
                        studentGradeQueryWrapper2.ne("lesson_type", 1);
                        studentGradeQueryWrapper2.eq("subjects_id", orderDetail.getSubjectsId());
                        iStudentGradeService.remove(studentGradeQueryWrapper2);
                    } catch (Exception ex) {
                        System.err.println(ex.getMessage());
                    }

                    //剩余课时为0，表示全部退出
                    newOrderDetail.setReadingStatus(ReadingStatusEnum.RETREAT);

                    StudentGrade studentGrade = iStudentGradeService.getById(orderDetail.getId());
                    if (studentGrade != null) {
                        if (studentGrade.getUseCourseCount() == 0) {
                            iStudentSchoolService.removeById(studentGrade);
                        }
                    }

                    //把所在班级设置为退费状态
                    UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                    studentGradeUpdateWrapper.eq("school_id", orderDetail.getSchoolId());
                    studentGradeUpdateWrapper.eq("year_part", orderDetail.getYearPart());
                    studentGradeUpdateWrapper.eq("quarter_num", orderDetail.getQuarterNum());
                    studentGradeUpdateWrapper.eq("subjects_id", orderDetail.getSubjectsId());
                    studentGradeUpdateWrapper.eq("student_id", orderDetail.getStudentId());
                    studentGradeUpdateWrapper.in("reading_status", 1, 4, 5);
                    studentGradeUpdateWrapper.set("reading_status", ReadingStatusEnum.RETREAT.getKey());
                    iStudentGradeService.update(null, studentGradeUpdateWrapper);

                    /**
                     * 缴费信息
                     */
                    QueryWrapper<RatePay> ratePayQueryWrapper = new QueryWrapper<>();
                    ratePayQueryWrapper.eq("order_id", orderTransferDetail.getOldOrderId());
                    iRatePayService.remove(ratePayQueryWrapper);

                    QueryWrapper<LackCourseLog> lackCourseLogQueryWrapper = new QueryWrapper<>();
                    lackCourseLogQueryWrapper.eq("student_id", orderDetail.getStudentId());
                    lackCourseLogQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
                    lackCourseLogQueryWrapper.eq("year_part", orderDetail.getYearPart());
                    lackCourseLogQueryWrapper.eq("lesson_type", orderDetail.getLessonType());
                    lackCourseLogQueryWrapper.eq("quarter_num", orderDetail.getQuarterNum());
                    lackCourseLogQueryWrapper.ne("is_repair", 1);
                    iLackCourseLogService.remove(lackCourseLogQueryWrapper);

                } else if (courseHouse > 0) {
                    isAll = false;
                }

                //剩余课时
                newOrderDetail.setResidueCourseCount(courseHouse);//剩余课时
                BigDecimal outPrice = orderDetail.getOutPrice();//退出金额

                //累计退出金额
                BigDecimal allOutPrice = outPrice.add(orderTransferDetail.getOutPrice());
                newOrderDetail.setOutPrice(allOutPrice);
                newOrderDetail.setOutHouse(orderDetail.getOutHouse() + orderTransferDetail.getOutHouse());//累计退出课时
                //设置剩余金额
                BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                residuePrice = residuePrice.subtract(orderTransferDetail.getOutPrice());
                newOrderDetail.setResiduePrice(residuePrice);
                orderDetailMapper.updateById(newOrderDetail);

                //招生数据设置为退费,未上满两次课的，设置为退费
                Integer recordCount = iRecordCourseService.getRecordCountArrive(orderDetail.getYearPart(), orderDetail.getQuarterNum(), orderDetail.getStudentId(), orderDetail.getSubjectsId());
                if (recordCount < 2) {
                    Long orderId = orderDetail.getOrderId();
                    UpdateWrapper<EnrollInfo> enrollInfoUpdateWrapper = new UpdateWrapper<>();
                    enrollInfoUpdateWrapper.eq("order_id", orderId);
                    enrollInfoUpdateWrapper.set("is_return", 1);
                    enrollInfoMapper.update(null, enrollInfoUpdateWrapper);
                }
                Course course = iCourseService.getById(orderDetail.getCourseId());
                yearClassId = course.getYearClassId().getKey();
                subjectsIdSet.add(course.getSubjectsId().toString());
            } else {
                throw new CommonException(ResultCode.REFUND_COURSE_NOT);
            }
            iOrderTransferDetailService.save(orderTransferDetail);
        }

        try {
            // 获取最后一次上课记录的老师
            RecordCourse recordCourse = iRecordCourseService.getRecordCourseByLastThreeQuarter(yearPart, quarterNum, 1, orderApply.getStudentId(), String.valueOf(subjectsId));
            if (recordCourse != null) {
                // 保存上课老师到表中
                OrderReturnTeacher orderReturnTeacher = new OrderReturnTeacher();
                orderReturnTeacher.setOrderId(orderApply.getId());
                orderReturnTeacher.setTeacherId(recordCourse.getOldTeacherId());
                iOrderReturnTeacherService.save(orderReturnTeacher);
            }
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }

        if (isAll == true) {
            //由于有的订单没有分班所以要做如下状态改变
            Long outCourseId = orderApply.getOrderTransfer().getOutGradeId();//转出课程id
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("school_id", orderApply.getSchoolId());
            studentGradeQueryWrapper.eq("student_id", orderApply.getStudentId());
            studentGradeQueryWrapper.eq("course_id", outCourseId);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 1);

            List<StudentGrade> studentGradeListUp = iStudentGradeService.list(studentGradeQueryWrapper);
            for (StudentGrade studentGrade : studentGradeListUp) {
                if (studentGrade.getUseCourseCount() == 0) {
                    iStudentSchoolService.removeById(studentGrade);
                } else {
                    studentGrade.setReadingStatus(ReadingStatusEnum.RETREAT);
                    iStudentGradeService.updateById(studentGrade);
                }
            }
        }

        orderApply.setYearPart(yearPart);
        orderApply.setQuarterNum(quarterNum);
        orderApply.setTradeContent(tradeContent);
        orderApply.setYearClassId(yearClassId);
        if (subjectsIdSet.size() > 0) {
            String subjectsIds = String.join(",", subjectsIdSet);
            orderApply.setSubjectsIdStr(subjectsIds);
        }

        orderApplyMapper.updateById(orderApply);

        return orderApply;
    }
}
